import { writeFile, mkdir } from 'fs/promises';
import { existsSync } from 'fs';
import { NextRequest, NextResponse } from 'next/server';
import { join } from 'path';
import { revalidateTag } from 'next/cache';

// 批量上传文件接口
export async function POST(request: NextRequest, { params }: { params: { slug: string[] } }) {
    try {
        const slug = params.slug || [];

        const formData = await request.formData();
        const files: File[] = formData.getAll('files') as unknown as File[];

        if (!files?.length) {
            return NextResponse.json({ error: 'File is required' }, { status: 400 });
        }
        const savePath = slug.filter((path) => path !== 'mirrors').filter(Boolean); // 文件保存的相对路径

        //文件根目录
        const rootPath = join(process.cwd(), process.env.FILE_LOCATION || '/');

        await Promise.all(
            files.map((file: File) => {
                return (async (file: File) => {
                    const bytes = await file.arrayBuffer();
                    const buffer = Buffer.from(bytes);

                    // 文件存放目录
                    const targetDir = join(rootPath, ...savePath);
                    if (!existsSync(targetDir)) {
                        await mkdir(targetDir);
                    }
                    const targetFile = join(targetDir, file.name);
                    await writeFile(targetFile, buffer);
                })(file);
            })
        );

        // revalidatePath(`/mirrors/${slug.join('/')}`);
        revalidateTag('mirrors');
        return NextResponse.json({ success: true, message: 'File uploaded successfully' });
    } catch (error) {
        console.error(error);
        return NextResponse.json({ success: false, message: 'File uploaded failed' });
    }
}
